using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Yoozoo.UI.YGUI;

namespace com.yoozoo.gta.Art
{
    public class TextureAtlasUVHandler : MonoBehaviour
    {
        private bool _spriteIsReady = false;
        private float _addTime = 0.0f;
        private void Update()
        {
#if !UNITY_EDITOR
            if (_spriteIsReady == false)
            {
                if (this.GetComponent<SpriteRenderer>())
                {
                    SpriteRenderer thisSpriteRenderer = this.GetComponent<SpriteRenderer>();
                    UVHandlerSR(thisSpriteRenderer);
                }
                else if (this.GetComponent<YImage>())
                {
                    YImage thisSpriteRenderer = this.GetComponent<YImage>();
                    UVHandlerY(thisSpriteRenderer);
                }
            }
#endif
        }
        private void UVHandlerSR(SpriteRenderer thisSpriteRenderer)
        {
            if (thisSpriteRenderer.material == null)
            {
                return;
            }
            Sprite thisSprite = thisSpriteRenderer.sprite;

            if (thisSprite != null)
            {
                Vector4 UVRect = UnityEngine.Sprites.DataUtility.GetOuterUV(thisSprite);
                thisSpriteRenderer.material.SetVector("_UVRect",UVRect);
                _addTime += Time.deltaTime;
                if (_addTime >=2.0f)
                {
                    //延迟停止，因为测试发现thisSprite刚加载出来第一次判断不为空的时候拿到的UVRect还是错的。
                    _spriteIsReady = true;
                }
            }
        }
        private void UVHandlerY(YImage thisSpriteRenderer)
        {
            if (thisSpriteRenderer.material == null)
            {
                return;
            }
            Sprite thisSprite = thisSpriteRenderer.sprite;
            if (thisSprite != null)
            {
                Vector4 UVRect = UnityEngine.Sprites.DataUtility.GetOuterUV(thisSprite);
                thisSpriteRenderer.material.SetVector("_UVRect",UVRect);
                _addTime += Time.deltaTime;
                if (_addTime >=2.0f)
                {
                    //延迟停止
                    _spriteIsReady = true;
                }
            }
        }

    }
}
